using System.IO;
using System.Linq;
using Core.Runtime;
using UnityEditor;
using UnityEngine;
using AssetDatabase = UnityEditor.AssetDatabase;

namespace Core.Editor
{
    public static class ScriptCreator
    {

        [MenuItem("Assets/Create/UIBase", false, 0)]
        public static void CreateUIBase()
        {
            var guid = AssetDatabase.FindAssets("t:GameSettingSo").FirstOrDefault();
            if (guid == null)
            {
                var asset = ScriptableObject.CreateInstance<GameSettingSo>();
                AssetDatabase.CreateAsset(asset, "Assets/GameSettingSo.asset");
                AssetDatabase.Refresh();
                guid = AssetDatabase.FindAssets("t:GameSettingSo").FirstOrDefault();
            }
            var path = AssetDatabase.GUIDToAssetPath(guid);
            var setting = AssetDatabase.LoadAssetAtPath<GameSettingSo>(path);
            if (setting.UIBaseTemplate == null)
            {
                Debug.LogError("请设置模板文件，模板文件中 #SCRIPTNAME# 将被文件名替换", setting);
                return;
            }
            var templatePath = AssetDatabase.GetAssetPath(setting.UIBaseTemplate.GetInstanceID());
            ProjectWindowUtil.CreateScriptAssetFromTemplateFile(Path.Combine(Application.dataPath, "..", templatePath), "NewUIBase.cs");
        }

        [MenuItem("Assets/Create/EventBase", false, 0)]
        public static void CreateEventBase()
        {
            var guid = AssetDatabase.FindAssets("t:GameSettingSo").FirstOrDefault();
            if (guid == null)
            {
                var asset = ScriptableObject.CreateInstance<GameSettingSo>();
                AssetDatabase.CreateAsset(asset, "Assets/GameSettingSo.asset");
                AssetDatabase.Refresh();
                guid = AssetDatabase.FindAssets("t:GameSettingSo").FirstOrDefault();
            }
            var path = AssetDatabase.GUIDToAssetPath(guid);
            var setting = AssetDatabase.LoadAssetAtPath<GameSettingSo>(path);
            if (setting.EventBaseTemplate == null)
            {
                Debug.LogError("请设置模板文件，模板文件中 #SCRIPTNAME# 将被文件名替换", setting);
                return;
            }
            var templatePath = AssetDatabase.GetAssetPath(setting.EventBaseTemplate.GetInstanceID());
            ProjectWindowUtil.CreateScriptAssetFromTemplateFile(Path.Combine(Application.dataPath, "..", templatePath), "NewUIComponent.cs");
        }
        
    }
}